package com.xunua.networkproject.Okhttp;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xunua.networkproject.R;
import com.xunua.networkproject.Utils.FileUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * @user XUNUA
 * @email  xunua@outlook.com
 * @creat time 2020/5/3 16:34
 *
 * 后台的下载地址  https://gitee.com/sunofbeaches/SOBAndroidMiniWeb
 *
 */
public class OkHttpActivity extends AppCompatActivity {
//    private String baseUrl="http://10.0.2.2:9102";//同电脑的虚拟机使用的ip地址
    private String baseUrl="http://192.168.1.104:9102";//同局域网中手机使用的IP地址   ip是电脑的内网ip
    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Toast.makeText(OkHttpActivity.this, ""+msg.obj.toString(), Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http);
    }

    void Toast(String s){
        Message obtain = Message.obtain();
        obtain.obj=s;
        handler.sendMessage(obtain);
    }


    public void get(View view) {
        //要有客户端
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5000, TimeUnit.MILLISECONDS)
                .build();

        //创建请求内容
        Request request = new Request.Builder()
                .get()
                .url(baseUrl + "/get/text")//无参get请求
//                .url(baseUrl + "/get/param?keyword=你好&page=1&order=1")//带参get请求
                .build();
        //用client创建请求任务

        //1、异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Toast("请求失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.code()==200) {
                    Toast("请求成功："+response.body().string());
                }
            }
        });
        //2、同步请求 execute()      因为不允许网络请求在主线程中执行   因此需要new 一个子线程
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Response response = client.newCall(request).execute();
//                    if (response.code() == 200) {
//                        Toast("请求成功："+response.body().string());
//                    }else {
//                        Toast("请求失败");
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
    }

    public void post(View view) {
        //要有客户端
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
        //需要提交的内容
        Ok3Bean ok3Bean = new Ok3Bean("123456", "我在学习post  嗯呢！");
        String json = new Gson().toJson(ok3Bean);
        MediaType mediaType = MediaType.parse("application/json");//Mime类型
        RequestBody requestBody = RequestBody.create(json, mediaType);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(baseUrl + "/post/comment")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Toast("请求失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.code() == 200) {
                    Toast("Post请求成功："+response.body().string());
                }
            }
        });
    }

    public void upload(View view) {
        performFileSearch();
    }

    private static final int REQUEST_CODE_CHOOSE = 43;
    public void uploads(View view) {
        Matisse.from(this)
                .choose(MimeType.ofAll())
                .countable(true)
                .maxSelectable(9)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .showPreview(true) // Default is `true`
                .forResult(REQUEST_CODE_CHOOSE);
    }

    public void download(View view) {
        OkHttpClient client = new OkHttpClient.Builder()
                .callTimeout(10000,TimeUnit.MILLISECONDS)
                .build();
        Request request = new Request.Builder()
                .get()
                .url(baseUrl + "/download/15")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    String name = headers.name(i);
                    String value = headers.value(i);
                    Log.e("TAG", name+"==="+value );
                }
                String fileName = headers.get("Content-disposition").replace("attachment; filename=", "");


                ContentResolver contentResolver = getApplicationContext().getContentResolver();
                Uri contentUri = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
                ContentValues contentValues = new ContentValues();
                contentValues.put(MediaStore.Images.Media.DISPLAY_NAME,fileName);//文件名
                contentValues.put(MediaStore.Images.Media.MIME_TYPE,"image/*");//文件类型1
                String FileDir="王者荣耀";
                contentValues.put(MediaStore.Images.Media.RELATIVE_PATH,"Pictures/"+FileDir);
                Uri insert = contentResolver.insert(contentUri, contentValues);
                if (insert == null) {
                    Log.e("TAG", "onResponse: 异常");
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OutputStream outputStream = null;
                        try {
                            outputStream = contentResolver.openOutputStream(insert);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        InputStream inputStream=response.body().byteStream();
                        try {
                            byte[] bytes = new byte[1024*2];
                            int len;
                            while ((len=inputStream.read(bytes))!=-1){
                                outputStream.write(bytes,0,len);
                            }
                            outputStream.flush();
                        }catch (IOException e){
                            Log.e("TAG", "onResponse: "+e );
                        }finally {
                            try {
                                outputStream.close();
                                inputStream.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode){
                case READ_REQUEST_CODE://上传一张图片
                    Uri uri;
                    if (data != null) {
                        uri = data.getData();
                        Log.e("TAG", "onActivityResult: "+uri );
                        upload(uri);
                    }
                    break;
                case REQUEST_CODE_CHOOSE://上传多张图片
                    List<Uri> result = Matisse.obtainResult(data);
                    uploads(result);
                    Log.e("TAG", "Uri: "+result.toString() );
                    break;
            }
        }
    }

    private static final int READ_REQUEST_CODE = 42;
    /**
     * Fires an intent to spin up the "file chooser" UI and select an image.
     * 选取单个图片
     */
    public void  performFileSearch() {

        // ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file
        // browser.
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

        // Filter to only show results that can be "opened", such as a
        // file (as opposed to a list of contacts or timezones)
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        // Filter to show only images, using the image MIME data type.
        // If one wanted to search for ogg vorbis files, the type would be "audio/ogg".
        // To search for all documents available via installed storage providers,
        // it would be "*/*".
        intent.setType("image/*");
//        intent.setType("video/*");
        startActivityForResult(intent, READ_REQUEST_CODE);
    }

    private Bitmap getBitmapFromUri(Uri uri) throws IOException {
        ParcelFileDescriptor parcelFileDescriptor =
                getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
        return image;
    }


    private String readTextFromUri(Uri uri) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        try (InputStream inputStream =
                     getContentResolver().openInputStream(uri);
             BufferedReader reader = new BufferedReader(
                     new InputStreamReader(Objects.requireNonNull(inputStream)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        return stringBuilder.toString();
    }
    //OkHttp上传单个文件
    void upload(Uri uri){
        InputStream inputStream=null;
        try {
            //client
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(10000, TimeUnit.MILLISECONDS)
                    .build();


            String path = FileUtils.getPath(this, uri);//通过uri得到了文件的绝对路径
            File file = new File(path);//特定新建一个file类
            String fileName = file.getName();//来获取文件名  主要是文件名的后缀
            inputStream = getContentResolver().openInputStream(uri);

            byte[] bytes = FileUtils.toByteArray(inputStream);

            String type = getContentResolver().getType(uri);
            RequestBody requestBody = RequestBody.create(bytes, MediaType.parse(type));
            MultipartBody multipartBody = new MultipartBody.Builder()
                    .addFormDataPart("file",fileName, requestBody)
                    .build();
            Request request = new Request.Builder()
                    .url(baseUrl+"/file/upload")
                    .post(multipartBody)
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    Toast("请求失败"+e);
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    Toast("成功了："+response.body().string());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.e("TAG", "Uri: "+uri.toString() );
    }
    //OkHttp上传多个文件      支持上传视频
    void uploads(List<Uri> uris){
        InputStream inputStream=null;
        try {
            //client
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(10000, TimeUnit.MILLISECONDS)
                    .build();
            MultipartBody.Builder mulBuilder = new MultipartBody.Builder();
            for (Uri uri:
                    uris) {
                String path = FileUtils.getPath(this,uri);
                File file = new File(path);
                String fileName = file.getName();
                inputStream=getContentResolver().openInputStream(uri);
                byte[] bytes = FileUtils.toByteArray(inputStream);
                Log.e("TAG", "onActivityResult: "+getContentResolver().getType(uri));
                RequestBody requestBody = RequestBody.create(bytes, MediaType.parse(getContentResolver().getType(uri)));
                mulBuilder.addFormDataPart("files",fileName,requestBody);
            }
            MultipartBody multipartBody = mulBuilder.build();
            Request request = new Request.Builder()
                    .url(baseUrl+"/files/upload")
                    .post(multipartBody)
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    Toast("请求失败");
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    Toast("成功了："+response.body().string());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @user XUNUA
     * @email xunua@outlook.com
     * @creat time 2020/5/3 16:22
     */
    public class Ok3Bean {

        /**
         * articleId : 234123
         * commentContent : 这是评论内容
         */

        private String articleId;
        private String commentContent;

        public Ok3Bean(String articleId, String commentContent) {
            this.articleId = articleId;
            this.commentContent = commentContent;
        }

        public String getArticleId() {
            return articleId;
        }

        public void setArticleId(String articleId) {
            this.articleId = articleId;
        }

        public String getCommentContent() {
            return commentContent;
        }

        public void setCommentContent(String commentContent) {
            this.commentContent = commentContent;
        }
    }

}
